<?php
//
//	file: includes/advlog/advlog_functions.php
//	begin: 30/04/2007
//	$Author: christopher $
//	$Revision: 31 $
//	$Date: 2008-07-21 03:08:30 +0000 (Mon, 21 Jul 2008) $
//	license: http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
//
//	description: loader for advanced logging

if (!defined('IN_PHPBB'))
{
	die("Hacking attempt");
}

if ( !defined('get_var') )
{
	// get_var : read $_POST/GET vars
	function get_var($var_name, $default, $multibyte = false)
	{
		global $HTTP_POST_VARS, $HTTP_GET_VARS;

		$request_var = (isset($HTTP_POST_VARS[$var_name])) ? $HTTP_POST_VARS : $HTTP_GET_VARS;
		if ( !isset($request_var[$var_name]) || (is_array($request_var[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($request_var[$var_name])) )
		{
			return is_array($default) ? array() : $default;
		}

		// get type from default
		if ( !is_array($default) )
		{
			$type = gettype($default);
		}
		else
		{
			list($key_type, $type) = each($default);
			$type = gettype($type);
			$key_type = gettype($key_type);
		}

		// get value
		$var = $request_var[$var_name];
		if ( !is_array($var) )
		{
			_set_var($var, $var, $type, $multibyte);
		}
		else
		{
			$_var = $var;
			$var = array();
			foreach ($_var as $k => $v)
			{
				_set_var($k, $k, $key_type);
				if ( !is_array($v) )
				{
					_set_var($var[$k], $v, $type, $multibyte);
				}
				else
				{
					foreach ($v as $_k => $_v)
					{
						_set_var($_k, $_k, $key_type);
						_set_var($var[$k][$_k], $_v, $type, $multibyte);
					}
				}
			}
		}
		return $var;
	}

	// _set_var : type cast for get_var()
	function _set_var(&$result, $var, $type, $multibyte = false)
	{
		settype($var, $type);
		$result = $var;

		if ($type == 'string')
		{
			$result = trim(htmlspecialchars(str_replace(array("\r\n", "\r", '\xFF'), array("\n", "\n", ' '), $result)));
			// 2.0.x is doing addslashes on all variables
			$result = stripslashes($result);
			if ($multibyte)
			{
				$result = preg_replace('#&amp;(\#[0-9]+;)#', '&\1', $result);
			}
		}
	}
}

if ( !defined('get_users_by_auth') )
{
	// get_users_by_auth : find users in with auth for $auth in $forum_id
	function get_users_by_auth($auth, $forum_id)
	{
		global $db;

		$ret = array();
		$sql = 'SELECT DISTINCT u.user_id, u.username, u.user_email, u.user_lang, MAX(a.auth_value) AS auth_solved
				FROM ' . USERS_TABLE . ' u
					LEFT JOIN ' . USER_GROUP_TABLE . ' as ug on u.user_id = ug.user_id
					LEFT JOIN ' . GROUPS_TABLE . ' as g on g.group_id = ug.group_id
					LEFT JOIN ' . AUTHS_TABLE . ' as a on g.group_id = a.group_id
				WHERE a.obj_type = \'' . POST_FORUM_URL . '\'
					AND a.obj_id = \'' . intval($forum_id) . '\'
					AND a.auth_name = \'' . $auth . '\'
					AND a.auth_value > 0
				GROUP BY u.user_id
				HAVING '. $db->sql_col_id('MAX(auth_value)', 'auth_solved') . ' IN(1, ' . FORCE . ')';
		$result = $db->sql_query($sql, false, __LINE__, __FILE__);
		while ( $row = $db->sql_fetchrow($result) )
		{
			$ret[$row['user_id']] = $row;
		}
		$db->sql_freeresult($result);

		return $ret;
	}
}

if ( !defined('send_email') )
{
	// send email : common emailer
	function send_email($users, $tpl, $tpl_data, $subject, $lang_tpl='')
	{
		global $config, $user;

		$bcc_list_ary = array();

		foreach ($users as $id => $row)
		{
			if ($row['user_email'] != '')
			{
				$bcc_list_ary[$row['user_lang']][] = $row['user_email'];
			}
		}

		// now we have a list of emails and languages to use
		if (sizeof($bcc_list_ary))
		{
			include_once($config->url('includes/emailer'));
			$emailer = new emailer($config->data['smtp_delivery']);


			@reset($bcc_list_ary);
			while (list($user_lang, $bcc_list) = each($bcc_list_ary))
			{
				// set template
				$emailer->use_template($tpl, $user_lang);
				$emailer->assign_vars($tpl_data + array(
					'EMAIL_SIG' => (!empty($config->data['board_email_sig'])) ? str_replace('<br />', "\n", "-- \n" . $config->data['board_email_sig']) : '',
					'SITENAME' => $config->data['sitename'],
				));

				for ($i = 0; $i < count($bcc_list); $i++)
				{
					$emailer->bcc($bcc_list[$i]);
				}

				// get lang file if we need to
				if ($lang_tpl)
				{
					if ($user_lang == '' || !$user_lang)
					{
						$user_lang = $config->data['default_lang'];
					}
					if ($user_lang != $user->lang_used)
					{
						$file = $config->url('language/lang_' . $user_lang . '/' . $lang_tpl);
					}
					if (!$file || !file_exists($file))
					{
						$file = $config->url('language/lang_' .$user->lang_used . '/' . $lang_tpl);
					}
					@include($file);
				}

				if ($lang)
				{
					$subject = $lang[$subject];
				}
				else
				{
					$subject = $user->lang($subject);
				}

				$emailer->set_subject($subject);
				$emailer->from($config->data['board_email']);
				$emailer->replyto($config->data['board_email']);

				$emailer->send();
				$emailer->reset();
			}
		}
		return;
	}
}

if ( !defined('get_table_by_field') )
{
	// get_count_by_field : Get a count of all entries in $table which match $data[value] of $data[field]
	function get_count_by_field($table, $data, $file=__FILE__, $line=__LINE__)
	{
		global $db;

		$data['counter'] = (empty($data['counter'])) ? '*' : $data['counter'];

		$sql = 'SELECT COUNT(' . $data['counter'] . ') AS total_count FROM ' . $table . ' WHERE ' . $data['key'] . ' = "' . $data['value'] . '"';
		if ($data['exclude_key'])
		{
			$sql .= ' AND ' . $data['exclude_key'] . ' != "' . $data['exclude_value'] . '"';
		}

		$result = $db->sql_query($sql, false, __LINE__, __FILE__, false);
		$ret = ($row = $db->sql_fetchrow($result)) ? intval($row['total_count']) : 0;
		$db->sql_freeresult($result);

		return $ret;
	}

	/* get_table_by_field: Get all $data[key] and $data[extra] from $table that match
	 * $data[value] of $data[key] excluding those that match $data[exclude_value] of
	 * $data[exclude_key] and orders by $data[order], $data[start], and $data[limit]
	 */
	function get_table_by_field($table, $data, $file=__FILE__, $line=__LINE__)
	{
		global $db;

		$sql = 'SELECT ' . $db->sql_fields('fields', array($data['key']) + $extra) . ' FROM '. $table . ' WHERE ' . $data['key'] . ($data['value_in']) ? ' IN (' . $data['value_in'] . ')' : ' = "' . $data['value'] . '"';
		if ($data['include_key'])
		{
			$sql .= ' AND ' . $data['include_key'] . ' = "' . $data['include_value'] . '"';
		}
		if ($data['exclude_key'])
		{
			$sql .= ' AND ' . $data['exclude_key'] . ' != "' . $data['exclude_value'] . '"';
		}
		if ($data['group'])
		{
			$sql .= ' GROUP BY ' . $data['group'];
		}
		if (!empty($order))
		{
			$sql .= ' ORDER BY ' . $order['by'] . ' ' . ($order['asc'] == true) ? 'ASC' : 'DESC';
			if (!empty($order['start']))
			{
				$sql .= ' LIMIT ' . $order['start'] . ', ' . $order['limit'];
			}
		}

		return $db->sql_query($sql, false, $line, $file, true);
	}
}

if ( !defined('external_url') )
{
	function external_url($basename, $parms=array(), $fragments='')
	{
		global $config;

		$url = $config->url($basename, $parms, false, $fragments);

		// strip relative path from url
		$len = strlen($config->root);
		return $config->get_script_path . substr($url, $len-1);
	}

?>